/**
 * 神州信息(2013)
 */
/**
 * 神州信息(2013)
 */
package net.nextvisual.report.start;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JProgressBar;
import javax.swing.SwingUtilities;
import javax.swing.filechooser.FileFilter;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.VerticalAlignment;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.abbp.core.util.NumberUtils;
import net.abbp.core.util.StringUtils;
import net.abbp.report.model.Cell;
import net.abbp.report.model.ReportModel;
import net.abbp.report.model.cell.style.HorizentalAlignment;
import net.abbp.report.model.cell.style.Style;
import net.abbp.report.utils.Dom4jUtils;
import net.abbp.report.view.GridView;
import net.abbp.swing.util.GuiUtils;

import org.dom4j.Document;
import org.dom4j.Element;

import com.reportgear.core.swing.pane.base.JBaseDialog;
import com.reportgear.designer.pane.style.GlobalStyleDialog;
import com.reportgear.report.model.auxiliary.RowType;
import com.reportgear.report.print.PreviewPane;
import com.reportgear.report.print.Printer;
import com.reportgear.report.print.ReportPage;
import com.reportgear.report.print.ReportPageIterator;
import com.reportgear.report.print.pane.PageSetupPane;
import com.reportgear.report.setting.PaperSetting;
import com.reportgear.report.setting.ReportSettings;

/**
 * 打印显示面板
 * 
 * @version 1.0
 * @author <a herf="lexloo@gmail.com">lexloo</a>
 * @since 销售宝 2.0
 * 
 *        <pre>
 * 历史：
 *      建立: 2013-8-6 lexloo
 * </pre>
 */
public class PrintShowPane extends JPanel {
    /**
     * UID
     */
    private static final long serialVersionUID = -9156397908738831575L;
    /**
     * 工具栏
     */
    private JPanel pnlToolbar;
    /**
     * 视图
     */
    private GridView view;
    /**
     * 模型
     */
    private ReportModel model = new ReportModel();
    // /**
    // * 是否分页
    // */
    // private boolean paging = false;
    // /**
    // * 分页类型
    // */
    // private int pageType;
    /**
     * 分页列，对应组织结构或成本中心列
     */
    private int pageColumn;
    /**
     * 数据类型键，文本型(T),数字型(N)
     */
    private List<String> dataTypeKey = new ArrayList<String>();
    /**
     * 列信息
     */
    private List<String> columnList = new ArrayList<String>();
    /**
     * 列选择状态
     */
    private List<Boolean> columnStatus = new ArrayList<Boolean>();
    /**
     * 标题
     */
    private String title;
    /**
     * 日期串
     */
    private String date;
    /**
     * 进度条
     */
    private JProgressBar pbr;

    /**
     * 数据集
     */
    private List<List<String>> data;
    /**
     * 头信息
     */
    private List<List<HeadCell>> headerInfos;
    /**
     * 显示0值按钮
     */
    private JButton btnClearZero = new JButton("清除0值");;

    /**
     * 构造函数
     */
    public PrintShowPane() {
        this.setLayout(new BorderLayout());

        this.pnlToolbar = this.createToolBar();
        this.add(this.pnlToolbar, BorderLayout.NORTH);

        this.view = new GridView(this.model);
        this.add(view);
    }

    /**
     * 设置列选择属性
     * 
     * @param status 列选择属性
     */
    public void setColumnStatus(List<Boolean> status) {
        pbr.setVisible(true);
        pbr.setIndeterminate(true);

        for (int i = 0, size = status.size(); i < size; i++) {
            if (status.get(i)) {
                if (this.model.getColumnWidth(i) == 0) {
                    this.model.setColumnWidth(i, 100);
                }
            } else {
                this.model.setColumnWidth(i, 0);
            }
        }

        this.updateUI();
        this.columnStatus = status;

        pbr.setVisible(false);
    }

    /**
     * 设置XmlData
     * 
     * @param dataXml xmlData
     * @param title 标题
     * @param date 日期
     */
    public void setXmlData(String dataXml, String title, String date) {
        this.title = title;
        this.date = date;
        Document doc = Dom4jUtils.createDocument(dataXml);
        Element root = doc.getRootElement();
        Element header = root.element("header");
        this.parseHeader2(header);
        this.parseColumnInfo(headerInfos);
        this.parseDateType(headerInfos);

        this.parseData(root.element("tbody"));

        this.loadData();
    }

    /**
     * 解析数据
     * 
     * @param tbody 元素
     */
    private void parseData(Element tbody) {
        this.data = new ArrayList<List<String>>();

        @SuppressWarnings("unchecked")
        List<Element> rows = tbody.elements("tr");
        for (Element r : rows) {
            @SuppressWarnings("unchecked")
            List<Element> columns = r.elements("td");
            List<String> rData = new ArrayList<String>();
            for (Element el : columns) {
                rData.add(el.getTextTrim());
            }
            this.data.add(rData);
        }
    }

    /**
     * 显示数据
     * 
     * @param xmlData 数据
     */
    private void loadData() {
        this.model.clear();
        this.pageColumn = this.parsePageColumn(this.headerInfos);
        this.sortData();

        List<Cell> headerList = this.parseHeadCells(this.headerInfos);
        for (Cell c : headerList) {
            this.model.addCell(c);
        }
        // 设置行属性
        for (int i = 0, size = this.headerInfos.size(); i < size; i++) {
            this.model.setRowType(i, RowType.HEADER);
        }
        int ptR = this.headerInfos.size();
        for (List<String> row : this.data) {
            for (int i = 0, size = row.size(); i < size; i++) {
                Cell c = new Cell(i, ptR, row.get(i));
                this.model.addCell(c);
            }
            ptR++;
        }

        this.view.updateUI();
        this.view.updateScrollBar();
    }

    /**
     * 数据排序
     */
    private void sortData() {
        this.pageColumn = this.parsePageColumn(headerInfos);
        if (this.pageColumn > -1) {
            Collections.sort(this.data, new Comparator<List<String>>() {

                @Override
                public int compare(List<String> vL1, List<String> vL2) {
                    return StringUtils.convertToString(vL1.get(pageColumn)).compareTo(vL2.get(pageColumn));
                }
            });
        }
    }

    /**
     * 更新数据
     */
    private void updateData() {
        int ptR = this.headerInfos.size();
        for (List<String> row : this.data) {
            for (int i = 0, size = row.size(); i < size; i++) {
                this.model.setCellValue(i, ptR, row.get(i));
            }
            ptR++;
        }

        this.view.updateUI();
    }

    /**
     * 显示0数据
     * 
     * @param xmlData 数据
     */
    private void showZeroValue() {
        int minDataRow = this.headerInfos.size();
        for (Iterator<Cell> itr = this.model.getCellIterator(); itr.hasNext();) {
            Cell c = itr.next();
            if (c.getRow() < minDataRow) {
                continue;
            }

            String value = StringUtils.convertToString(c.getValue());
            if ("".equals(value)) {
                c.setValue("0");
            }
        }

        this.view.updateUI();
    }

    /**
     * 隐藏0数据
     * 
     * @param xmlData 数据
     */
    private void hideZeroValue() {
        int minDataRow = this.headerInfos.size();
        for (Iterator<Cell> itr = this.model.getCellIterator(); itr.hasNext();) {
            Cell c = itr.next();
            if (c.getRow() < minDataRow) {
                continue;
            }

            String value = StringUtils.convertToString(c.getValue());
            if ("0".equals(value)) {
                c.setValue("");
            }
        }

        this.view.updateUI();
    }

    /**
     * 解析列信息
     * 
     * @param headerInfo 列头信息
     */
    private void parseColumnInfo(List<List<HeadCell>> headerInfo) {
        List<HeadCell> lst = headerInfo.get(headerInfo.size() - 1);

        for (HeadCell hc : lst) {
            columnList.add(hc.getValue());
            columnStatus.add(true);
        }
    }

    /**
     * 解析列数据类型
     * 
     * @param headerInfo
     */
    private void parseDateType(List<List<HeadCell>> headerInfo) {
        this.dataTypeKey.clear();
        List<HeadCell> lastRow = headerInfo.get(headerInfo.size() - 1);
        for (HeadCell hc : lastRow) {
            this.dataTypeKey.add(hc.getDataType());
        }
    }

    /**
     * 解析分页列
     * 
     * @param headerInfo
     * @return
     */
    private int parsePageColumn(List<List<HeadCell>> headerInfo) {
        if (PageParameter.INSTANCE.isPaging()) {
            List<HeadCell> r0 = headerInfo.get(2);
            String compareValue = "";

            if (PageParameter.INSTANCE.getPageType() == Parameter.TYPE_CC) {
                compareValue = "成本中心";
            } else {
                compareValue = "部门";
            }

            for (int i = 0, size = r0.size(); i < size; i++) {
                if (StringUtils.convertToString(r0.get(i).getValue(), "").contains(compareValue)) {
                    return i;
                }
            }
        }

        return -1;
    }

    /**
     * 解析头部Cell
     * 
     * @param headerInfo
     * @return
     */
    private List<Cell> parseHeadCells(List<List<HeadCell>> headerInfo) {
        List<Cell> rtn = new ArrayList<Cell>();

        // 更新行列信息
        for (int r = 0, rc = headerInfo.size(); r < rc; r++) {
            List<HeadCell> row = headerInfo.get(r);
            for (int c = 0, cc = row.size(); c < cc; c++) {
                HeadCell hc = row.get(c);
                hc.setColumn(c);
                hc.setRow(r);
            }
        }

        // 处理列合并
        for (int r = 0, rc = headerInfo.size(); r < rc; r++) {
            List<HeadCell> row = headerInfo.get(r);
            for (int c = 0, cc = row.size(); c < cc; c++) {
                HeadCell hc = row.get(c);
                for (int k = c + 1; k < cc; k++) {
                    HeadCell hck = row.get(k);
                    if (StringUtils.convertToString(hck.getValue(), "").equals(hc.getValue())) {
                        hc.setColumnSpan(hc.getColumnSpan() + 1);
                        hck.setValue("^?^");
                    } else {
                        c = k - 1;
                        break;
                    }
                }
            }
        }

        // 处理行合并
        for (int r = 0, rc = headerInfo.size(); r < rc - 1; r++) {
            List<HeadCell> row = headerInfo.get(r);
            for (int c = 0, cc = row.size(); c < cc; c++) {
                HeadCell hc = row.get(c);
                if ("^?^".equals(hc.getValue())) {
                    continue;
                }

                for (int k = r + 1; k < rc; k++) {
                    HeadCell hck = headerInfo.get(k).get(c);
                    if (StringUtils.convertToString(hck.getValue(), "").equals(hc.getValue())
                        && hck.getColumnSpan() == hc.getColumnSpan()) {
                        hc.setRowSpan(hc.getRowSpan() + 1);
                        hck.setValue("^?^");
                    } else {
                        break;
                    }
                }
            }
        }

        /**
         * 输出单元格
         */
        for (List<HeadCell> row : headerInfo) {
            for (HeadCell c : row) {
                if (!"^?^".equals(c.getValue())) {
                    Cell cell = new Cell(c.getColumn(), c.getRow(), c.getValue());
                    cell.setRowSpan(c.getRowSpan());
                    cell.setColumnSpan(c.getColumnSpan());
                    if (c.getRow() == 0 || c.getRow() == 1) {// 设置边框为空
                        cell.setStyle(cell.getStyle().deriveBorder(0,
                                                                   Color.BLACK,
                                                                   0,
                                                                   Color.BLACK,
                                                                   0,
                                                                   Color.BLACK,
                                                                   0,
                                                                   Color.BLACK));
                    }
                    if (c.getRow() == 1) {// 设置第二行左对齐
                        cell.setStyle(cell.getStyle().derivetHorizentalAlignment(HorizentalAlignment.Left));
                    }
                    rtn.add(cell);
                }
            }
        }

        return rtn;
    }

    /**
     * 解析标题信息
     * 
     * @param header
     * @return
     */
    private void parseHeader2(Element header) {
        this.headerInfos = new ArrayList<List<HeadCell>>();
        @SuppressWarnings("unchecked")
        List<Element> row = header.elements("tr");
        for (int i = 0, size = row.size(); i < size; i++) {
            Element r = row.get(i);
            @SuppressWarnings("unchecked")
            List<Element> ths = r.elements("th");

            List<HeadCell> rowList = new ArrayList<HeadCell>();
            for (Element th : ths) {
                int rowSpan = NumberUtils.convertToInteger(th.attributeValue("rowspan"), 1);
                int columnSpan = NumberUtils.convertToInteger(th.attributeValue("colspan"), 1);
                String value = th.getTextTrim();

                HeadCell cell = new HeadCell(columnSpan, rowSpan, value);
                if ("decimal".equals(th.attributeValue("datatype"))) {
                    cell.setDataType("N");
                } else {
                    cell.setDataType("T");
                }
                rowList.add(cell);
            }
            headerInfos.add(rowList);
        }

        fillHeader(headerInfos);
        fillTitleDate(headerInfos);
    }

    /**
     * 填充标题和时间
     * 
     * @param rtn 当前对象
     */
    private void fillTitleDate(List<List<HeadCell>> rtn) {
        int size = rtn.get(rtn.size() - 1).size();

        List<HeadCell> lst = new ArrayList<HeadCell>();
        for (int i = 0; i < size; i++) {
            lst.add(new HeadCell(1, 1, this.title));
        }

        rtn.add(0, lst);

        lst = new ArrayList<HeadCell>();
        for (int i = 0; i < size; i++) {
            lst.add(new HeadCell(1, 1, this.date));
        }

        rtn.add(1, lst);
    }

    /**
     * @param rtn 处理的header
     */
    private void fillHeader(List<List<HeadCell>> rtn) {
        // 处理列,横向打散
        for (int i = 0, size = rtn.size(); i < size; i++) {
            List<HeadCell> row = rtn.get(i);
            for (int len = row.size(), j = len - 1; j >= 0; j--) {
                HeadCell cell = row.get(j);

                if (cell.getColumnSpan() > 1) {
                    for (int k = 0, count = cell.getColumnSpan() - 1; k < count; k++) {
                        HeadCell cc = new HeadCell(1, 1, cell.getValue());
                        cc.setDataType(cell.getDataType());
                        row.add(j + 1, cc);
                    }
                    cell.setColumnSpan(1);
                }
            }
        }

        // 处理行,纵向打散
        int colCount = rtn.get(0).size();
        for (int c = 0; c < colCount; c++) {
            for (int i = 0, size = rtn.size(); i < size; i++) {
                List<HeadCell> row = rtn.get(i);
                HeadCell cell = row.get(c);
                if (cell.getRowSpan() > 1) {
                    for (int k = 1; k < cell.getRowSpan(); k++) {
                        HeadCell cc = new HeadCell(1, 1, cell.getValue());
                        cc.setDataType(cell.getDataType());

                        rtn.get(i + k).add(c, cc);
                    }
                    cell.setRowSpan(1);

                    i = i + cell.getRowSpan() - 1;
                }
            }
        }
    }

    /**
     * @return 工具条
     */
    private JPanel createToolBar() {
        JPanel rtn = new JPanel(new FlowLayout(FlowLayout.LEFT));

        JButton btnPrintView = new JButton("打印预览");
        btnPrintView.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                PreviewPane preview = new PreviewPane();

                JFrame frame = new JFrame();
                frame.setMinimumSize(new Dimension(800, 600));
                frame.setPreferredSize(new Dimension(800, 600));
                frame.setLayout(new BorderLayout());

                if (pageColumn >= 0) {
                    preview.print(model, pageColumn);
                } else {
                    preview.print(model);
                }

                frame.add(preview, BorderLayout.CENTER);
                frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

                GuiUtils.centerWindow(frame);
                frame.setVisible(true);
            }
        });
        rtn.add(btnPrintView);

        JButton btnPrint = new JButton("打印");
        btnPrint.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                List<ReportPage> pages = new ArrayList<ReportPage>();
                Iterator<ReportPage> rs = new ReportPageIterator(model, pageColumn);
                while (rs.hasNext()) {
                    pages.add(rs.next());
                }

                new Printer().print(pages);
            }
        });
        rtn.add(btnPrint);

        JButton btnPageSetup = new JButton("页面设置");
        btnPageSetup.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                PageSetupPane psp = new PageSetupPane();
                psp.populate(model);

                int result = psp.showDialog(null);

                if (result == JBaseDialog.RESULT_OK) {
                    psp.update(model);

                    if (psp.updatePageInfo()) {
                        sortData();
                        updateData();
                    }
                }
            }
        });
        rtn.add(btnPageSetup);

        JButton btnExport = new JButton("导出");
        btnExport.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                Executors.newCachedThreadPool().execute(new Runnable() {

                    @Override
                    public void run() {
                        JFileChooser jf = new JFileChooser();
                        jf.setFileFilter(new FileFilter() {

                            @Override
                            public boolean accept(File f) {
                                if (f.isDirectory() || f.getName().toUpperCase().endsWith(".XLS")) {
                                    return true;
                                }
                                return false;
                            }

                            @Override
                            public String getDescription() {
                                return "Excel 文件";
                            }
                        });
                        int value = jf.showSaveDialog(null);

                        if (value == JFileChooser.APPROVE_OPTION) {
                            File file = jf.getSelectedFile();
                            String absoluteFileName = file.getAbsolutePath();
                            if (!absoluteFileName.endsWith(".xls")) {
                                absoluteFileName = absoluteFileName + ".xls";
                            }

                            export(new File(absoluteFileName));
                        }
                    }
                });
            }
        });
        rtn.add(btnExport);

        JButton btnMerge = new JButton("合并单元格");
        btnMerge.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (view != null) {
                    view.mergeCell();
                }
            }
        });
        rtn.add(btnMerge);

        JButton btnUnMerge = new JButton("拆分单元格");
        btnUnMerge.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (view != null) {
                    view.unmergeCell();
                }
            }
        });
        rtn.add(btnUnMerge);

        JButton btnSelectColumn = new JButton("选择列");
        btnSelectColumn.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                SelectColumnPane scp = new SelectColumnPane();
                scp.setColumns(columnList, columnStatus);
                scp.showInDialog(SwingUtilities.getWindowAncestor(PrintShowPane.this), "选择打印列");
                if (scp.getResult() == SelectColumnPane.OK) {
                    setColumnStatus(scp.getSelectStatus());
                }
            }
        });
        rtn.add(btnSelectColumn);

        btnClearZero.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JButton source = ((JButton) e.getSource());
                if ("清除0值".equals(source.getText())) {
                    source.setText("显示0值");
                    hideZeroValue();
                } else {
                    source.setText("清除0值");
                    showZeroValue();
                }
            }
        });
        rtn.add(btnClearZero);

        JButton btnLeft = new JButton("靠左");
        btnLeft.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                List<Cell> cells = view.getSelectedCells();
                for (Cell cell : cells) {
                    cell.setStyle(cell.getStyle().derivetHorizentalAlignment(HorizentalAlignment.Left));
                    view.updateUI();
                }
            }
        });
        rtn.add(btnLeft);

        JButton btnCenter = new JButton("居中");
        btnCenter.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                List<Cell> cells = view.getSelectedCells();
                for (Cell cell : cells) {
                    cell.setStyle(cell.getStyle().derivetHorizentalAlignment(HorizentalAlignment.Center));
                    view.updateUI();
                }
            }
        });
        rtn.add(btnCenter);

        JButton btnRight = new JButton("靠右");
        btnRight.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                List<Cell> cells = view.getSelectedCells();
                for (Cell cell : cells) {
                    cell.setStyle(cell.getStyle().derivetHorizentalAlignment(HorizentalAlignment.Right));
                    view.updateUI();
                }
            }
        });
        rtn.add(btnRight);

        JButton btnStyle = new JButton("样式");
        btnStyle.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                GlobalStyleDialog dlg = new GlobalStyleDialog();

                dlg.populateCellStyle(view);
                dlg.showModel();

                if (dlg.getReturnValue() == JBaseDialog.RESULT_OK) {
                    dlg.updateCellStyle(view);

                    view.updateUI();
                }
            }
        });
        rtn.add(btnStyle);

        pbr = new JProgressBar();
        pbr.setOrientation(JProgressBar.HORIZONTAL);
        pbr.setStringPainted(true);
        // pbr.addChangeListener(this);
        pbr.setPreferredSize(new Dimension(300, 24));
        pbr.setBorderPainted(true);
        pbr.setBackground(Color.PINK);
        pbr.setVisible(false);

        rtn.add(pbr);

        return rtn;
    }

    /**
     * 导出到文件
     * 
     * @param file
     */
    private void export(File file) {
        pbr.setVisible(true);
        pbr.setIndeterminate(false);
        pbr.setValue(0);
        pbr.setMinimum(0);
        pbr.setMaximum(model.getRowCount());

        // 输出数据
        try {
            Map<HorizentalAlignment, WritableCellFormat> fMap = getExportCellFormat();

            OutputStream os = new FileOutputStream(file);
            // 创建工作薄
            WritableWorkbook workbook = Workbook.createWorkbook(os);
            // 创建工作表
            final WritableSheet sheet = workbook.createSheet("报表", 0);

            for (int c = 0, cols = model.getColumnCount(); c < cols; c++) {
                sheet.setColumnView(c, model.getColumnWidth(c) / 7);
            }

            for (int r = 0, rows = model.getRowCount(); r < rows; r++) {
                sheet.setRowView(r, model.getRowHeight(r) * 15);
            }
            for (int r = 0, rows = model.getRowCount(); r < rows; r++) {
                for (int c = 0, cols = model.getColumnCount(); c < cols; c++) {
                    Cell cell = model.getCell(c, r);
                    if (cell == Cell.EMPTY_CELL) {
                        continue;
                    } else {
                        if (cell.isMerged()) {
                            sheet.mergeCells(c, r, c + cell.getColumnSpan() - 1, r + cell.getRowSpan() - 1);
                        }
                        Style style = cell.getStyle();
                        WritableCellFormat wcf = fMap.get(style.getHorizentalAlignment());

                        if ("N".equals(this.dataTypeKey.get(c))) {
                            try {
                                sheet.addCell(new jxl.write.Number(c,
                                                                   r,
                                                                   NumberUtils.convertToDouble(cell.getValue()),
                                                                   wcf));
                            } catch (Exception ex) {
                                sheet.addCell(new Label(c, r, StringUtils.convertToString(cell.getValue()), wcf));
                            }
                        } else {
                            sheet.addCell(new Label(c, r, StringUtils.convertToString(cell.getValue()), wcf));
                        }
                    }
                }

                pbr.setValue(r + 1);
            }

            // 移除隐藏的单元格
            for (int size = this.columnStatus.size(), i = size - 1; i >= 0; i--) {
                if (!this.columnStatus.get(i)) {
                    sheet.removeColumn(i);
                }
            }
            workbook.write();
            workbook.close();
            os.close();

            JOptionPane.showMessageDialog(null, "导出完成");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        pbr.setVisible(false);
    }

    /**
     * 导出格式
     * 
     * @return 导出格式
     */
    private Map<HorizentalAlignment, WritableCellFormat> getExportCellFormat() {
        Map<HorizentalAlignment, WritableCellFormat> rtn =
                new EnumMap<HorizentalAlignment, WritableCellFormat>(HorizentalAlignment.class);
        try {
            WritableCellFormat fm = new WritableCellFormat(NumberFormats.TEXT);
            fm.setBorder(Border.ALL, BorderLineStyle.THIN);
            fm.setVerticalAlignment(VerticalAlignment.CENTRE);
            fm.setAlignment(Alignment.LEFT);
            fm.setWrap(true);

            rtn.put(HorizentalAlignment.Left, fm);

            fm = new WritableCellFormat(NumberFormats.TEXT);
            fm.setBorder(Border.ALL, BorderLineStyle.THIN);
            fm.setVerticalAlignment(VerticalAlignment.CENTRE);
            fm.setAlignment(Alignment.CENTRE);
            fm.setWrap(true);

            rtn.put(HorizentalAlignment.Center, fm);

            fm = new WritableCellFormat(NumberFormats.TEXT);
            fm.setBorder(Border.ALL, BorderLineStyle.THIN);
            fm.setVerticalAlignment(VerticalAlignment.CENTRE);
            fm.setAlignment(Alignment.RIGHT);
            fm.setWrap(true);

            rtn.put(HorizentalAlignment.Right, fm);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return rtn;
    }

    /**
     * 设置参数
     * 
     * @param parameter 参数
     */
    public void setParameter(Parameter parameter) {
        if (this.model == null) {
            return;
        }

        ReportSettings rs = model.getReportSettings();
        PaperSetting ps = rs.getPaperSetting();
        ps.setOrientation(parameter.getOrientation());
        ps.setPaperSize(parameter.getPageSize());

        PageParameter.INSTANCE.setPaging(parameter.isTypePaging());
        PageParameter.INSTANCE.setPageType(parameter.getType());
    }
}
